package com.hj.reggie.dto.Ipml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hj.reggie.domain.Category;
import com.hj.reggie.domain.Setmeal;
import com.hj.reggie.dto.SetmealDto;
import com.hj.reggie.service.CategoryService;
import com.hj.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class SetmealDtoImpl {


    private final CategoryService categoryService;
    private final SetmealService setmealService;

    public SetmealDtoImpl(CategoryService categoryService, SetmealService setmealService) {
        this.categoryService = categoryService;
        this.setmealService = setmealService;
    }

    /**
     * @param page     页数
     * @param pageSize 页数展示条数
     * @param name     根据name like 查询相关满足条件的
     * @return 返回查询成功
     */

    public Page<SetmealDto> pageSetmeal(Integer page, Integer pageSize, String name) {
        //分页构造器对象
        Page<Setmeal> dishDtoPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //条件构造器
        Page<Setmeal> setmealPage = setmealService.page(dishDtoPage, new LambdaQueryWrapper<Setmeal>().like(name != null, Setmeal::getName, name).orderByDesc(Setmeal::getCreateTime).orderByDesc(Setmeal::getUpdateTime));
        //拷贝setmealPage内容忽略records
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        //处理records数据生成新的SetmealDto数据
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto> record = records.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            //拷贝setmeal数据到setmealDto中
            BeanUtils.copyProperties(setmeal, setmealDto);
            //查询根据菜品分类iD查询数据
            Category category = categoryService.getById(setmeal.getCategoryId());
            if (category != null) {
                String categoryName = category.getName();
                //把categoryName赋值给SetmealDto
                setmealDto.setCategoryName(categoryName);
            }
            //返回setmealDto对象
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(record);
        return setmealDtoPage;
    }
}
